<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="SummaryOfProjectForm">
          <!-- 移除 type="flex"，并将所有 a-col 的 span 设置为 24 -->
          <a-row>
            <a-col :span="24">
              <p>项目单位:</p>
              <a-form-item :labelAlign="'left'" size:small style="width: 140%" v-bind="validateInfos.orgCode" id="SummaryOfProjectForm-orgCode" name="orgCode">
                <j-dict-select-tag v-model:value="formData.orgCode" dictCode="org_code" placeholder="请选择所属部门" allow-clear  />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>项目名称:</p>
              <a-form-item style="width: 140%" v-bind="validateInfos.projectName" id="SummaryOfProjectForm-projectName" name="projectName">
                <a-textarea v-model:value="formData.projectName" placeholder="请输入项目名称" allow-clear style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>技术、经济考核指标:</p>
              <a-form-item style="width: 140%"
                           v-bind="validateInfos.assessmenIndicators"
                           id="SummaryOfProjectForm-assessmenIndicators"
                           name="assessmenIndicators">
                <a-textarea  v-model:value="formData.assessmenIndicators" :rows="2" placeholder="请输入技术、经济考核指标"  />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>核心示范规模:</p>
            </a-col>
            <a-col :span="24">
              <p>亩:</p>
              <a-form-item label="" v-bind="validateInfos.acresFocus" id="SummaryOfProjectForm-acresFocus" name="acresFocus" :labelAlign="'left'" >
                <a-input-number  v-model:value="formData.acresFocus" placeholder="请输入" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>袋:</p>
              <a-form-item label="" v-bind="validateInfos.bagFocus" id="SummaryOfProjectForm-bagFocus" name="bagFocus" :labelAlign="'left'">
                <a-input-number v-model:value="formData.bagFocus" placeholder="请输入"style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>头、只:</p>
              <a-form-item label="" v-bind="validateInfos.headFocus" id="SummaryOfProjectForm-headFocus" name="headFocus" :labelAlign="'left'">
                <a-input-number v-model:value="formData.headFocus" placeholder="请输入"style="width: 140%"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>栋:</p>
              <a-form-item label="" v-bind="validateInfos.buildingFocus" id="SummaryOfProjectForm-buildingFocus" name="buildingFocus" :labelAlign="'left'">
                <a-input-number v-model:value="formData.buildingFocus" placeholder="请输入" style="width: 140%"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>示范带动规模:</p>
            </a-col>
            <a-col :span="24">
              <p>亩:</p>
              <a-form-item label="" v-bind="validateInfos.acresPromote" id="SummaryOfProjectForm-acresPromote" name="acresPromote" :labelAlign="'left'">
                <a-input-number v-model:value="formData.acresPromote" placeholder="请输入" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>袋:</p>
              <a-form-item label="" v-bind="validateInfos.bagPromote" id="SummaryOfProjectForm-bagPromote" name="bagPromote" :labelAlign="'left'">
                <a-input-number v-model:value="formData.bagPromote" placeholder="请输入" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>头、只:</p>
              <a-form-item label="" v-bind="validateInfos.headPromote" id="SummaryOfProjectForm-headPromote" name="headPromote" :labelAlign="'left'">
                <a-input-number v-model:value="formData.headPromote" placeholder="请输入" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>栋:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.buildingPromote"
                id="SummaryOfProjectForm-buildingPromote"
                name="buildingPromote"
                :labelAlign="'left'"
              >
                <a-input-number v-model:value="formData.buildingPromote" placeholder="请输入" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>推广品种（个）:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.commercialVariety"
                id="SummaryOfProjectForm-commercialVariety"
                name="commercialVariety"
              >
                <a-input-number  v-model:value="formData.commercialVariety" placeholder="请输入推广品种" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>示范推广技术（项）:</p>
              <a-form-item label="" v-bind="validateInfos.dpTechnology" id="SummaryOfProjectForm-dpTechnology" name="dpTechnology">
                <a-input-number v-model:value="formData.dpTechnology" placeholder="请输入示范推广技术" style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>培训人数（人）:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.trainNumberPeople"
                id="SummaryOfProjectForm-trainNumberPeople"
                name="trainNumberPeople"
              >
                <a-input-number v-model:value="formData.trainNumberPeople" placeholder="请输入培训人数"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>发表论文（篇）:</p>
              <a-form-item label="" v-bind="validateInfos.publishPaper" id="SummaryOfProjectForm-publishPaper" name="publishPaper">
                <a-input-number v-model:value="formData.publishPaper" placeholder="请输入发表论文"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>工作宣传报道(篇):</p>
              <a-form-item
                label=""
                v-bind="validateInfos.workPromotionReport"
                id="SummaryOfProjectForm-workPromotionReport"
                name="workPromotionReport"
              >
                <a-input-number v-model:value="formData.workPromotionReport" placeholder="请输入工作宣传报道"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>专家团队技术服务（次）:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.expertServices"
                id="SummaryOfProjectForm-expertServices"
                name="expertServices"
              >
                <a-input-number v-model:value="formData.expertServices" placeholder="请输入专家团队技术服务"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>资金情况:</p>
            </a-col>
            <a-col :span="24">
              <p>总资金（万元）:</p>
              <a-form-item label="" v-bind="validateInfos.totalPrice" id="SummaryOfProjectForm-totalPrice" name="totalPrice">
                <a-input-number v-model:value="formData.totalPrice" placeholder="请输入总资金（万元）"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>补贴资金 （万元）:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.subsidyAmount"
                id="SummaryOfProjectForm-subsidyAmount"
                name="subsidyAmount"
              >
                <a-input-number v-model:value="formData.subsidyAmount" placeholder="请输入补贴资金 （万元）"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>配套资金 （万元）:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.complementAmount"
                id="SummaryOfProjectForm-complementAmount"
                name="complementAmount"
              >
                <a-input-number v-model:value="formData.complementAmount" placeholder="请输入配套资金 （万元）"  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>合作农场:</p>
              <a-form-item label="" v-bind="validateInfos.cooperativeFarm" id="SummaryOfProjectForm-cooperativeFarm" name="cooperativeFarm">
                <a-input v-model:value="formData.cooperativeFarm" placeholder="请输入合作农场"  allow-clear  style="width: 140%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>合作分公司:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.cooperativeBranch"
                id="SummaryOfProjectForm-cooperativeBranch"
                name="cooperativeBranch"
              >
                <a-input v-model:value="formData.cooperativeBranch" placeholder="请输入合作分公司" style="width: 140%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>示范基地:</p>
              <a-form-item
                label=""
                v-bind="validateInfos.demonstrationBase"
                id="SummaryOfProjectForm-demonstrationBase"
                name="demonstrationBase">
                <a-input v-model:value="formData.demonstrationBase" placeholder="请输入示范基地" style="width: 140%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>项目负责人:</p>
              <a-form-item label="" v-bind="validateInfos.projectLeader" id="SummaryOfProjectForm-projectLeader" name="projectLeader">
                <a-input v-model:value="formData.projectLeader" placeholder="请输入项目负责人" allow-clear style="width: 140%"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>联系人:</p>
              <a-form-item label="" v-bind="validateInfos.contactBy" id="SummaryOfProjectForm-contactBy" name="contactBy">
                <a-input v-model:value="formData.contactBy" placeholder="请输入联系人" allow-clear style="width: 140%"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>联系人电话:</p>
              <a-form-item label="" v-bind="validateInfos.contactNumber" id="SummaryOfProjectForm-contactNumber" name="contactNumber">
                <a-input v-model:value="formData.contactNumber" placeholder="请输入联系人电话" allow-clear style="width: 140%"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <p>项目类别:</p>
              <a-form-item label="" v-bind="validateInfos.projectType" id="SummaryOfProjectForm-projectType" name="projectType">
                <j-dict-select-tag v-model:value="formData.projectType" dict-code="project_type_code" placeholder="请选择项目类别" allow-clear style="width: 140%"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../SummaryOfProject.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true }
});
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  orgCode: '',
  projectName: '',
  assessmenIndicators: '',
  acresFocus: undefined,
  bagFocus: undefined,
  headFocus: undefined,
  buildingFocus: undefined,
  acresPromote: undefined,
  bagPromote: undefined,
  headPromote: undefined,
  buildingPromote: undefined,
  commercialVariety: undefined,
  dpTechnology: undefined,
  trainNumberPeople: undefined,
  publishPaper: undefined,
  workPromotionReport: undefined,
  expertServices: undefined,
  totalPrice: undefined,
  subsidyAmount: undefined,
  complementAmount: undefined,
  cooperativeFarm: '',
  cooperativeBranch: '',
  demonstrationBase: '',
  projectLeader: '',
  contactBy: '',
  contactNumber: '',
  projectType: undefined,
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    acresFocus: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    bagFocus: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    headFocus: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    buildingFocus: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    acresPromote: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    bagPromote: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    headPromote: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    buildingPromote: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    commercialVariety: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    dpTechnology: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    trainNumberPeople: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    publishPaper: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    workPromotionReport: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    expertServices: [{ required: false}, { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},],
    totalPrice: [{ required: false}, { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},],
    subsidyAmount: [{ required: false}, { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},],
    complementAmount: [{ required: false}, { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},],
    contactNumber: [{ required: false}, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });


  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
